package com.alinesno.cloud.base.storage.api;
import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alinesno.cloud.base.storage.enums.StorageStrategyEnums;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
    	
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:25003/storageFile/uploadFile");

            FileBody bin = new FileBody(new File("/Users/luodong/Desktop/demo_05.jpg"));
            StringBody strategy = new StringBody(StorageStrategyEnums.LOCAL.value(), ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("file", bin)
                    .addPart("strategy", strategy )
                    .build();

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();
                    if (statusCode == 200) { /**获取服务器返回的文本消息*/
                    	HttpEntity httpEntity = response.getEntity();
						String feedback = EntityUtils.toString(httpEntity, "UTF-8");
						System.out.println("feedback：" + feedback);
                    }
                    
                }
                EntityUtils.consume(resEntity);
                resEntity.getContent() ; 
                
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}